/*
 * Copyright (C) 2009 TeamCity Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.cdmdotnet.android.teamcity;

import static com.cdmdotnet.android.teamcity.IActions.ACTION_PICK_PROJECT;

import com.cdmdotnet.android.teamcity.R;

import android.app.ListActivity;
import android.appwidget.AppWidgetManager;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class ProjectWidgetConfigure extends ListActivity {
		
	static final int PICK_PROJECT_REQUEST = 0;
	static final int NEW_SERVER_REQUEST = 1;
	static final int EDIT_SERVER_REQUEST = 2;

	private static final String DB_FIELD_URI = "Uri";
	private static final String DB_FIELD_USERNAME = "Username";
	private static final String DB_FIELD_PASSWORD = "Password";

	private final String SERVERS_DATABASE_NAME = "TCServersDB"; 
	private final String SERVERS_DATABASE_TABLE = "t_Servers11"; 
		
    int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
	
	private SQLiteDatabase mServersDB;
	private SimpleCursorAdapter mAdapter;
	private Cursor mC;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Set the result to CANCELED.  This will cause the widget host to cancel
        // out of the widget placement if they press the back button.
        setResult(RESULT_CANCELED);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

		mAdapter = new SimpleCursorAdapter(this,
	            android.R.layout.simple_list_item_2, null, 
	            new String[] { DB_FIELD_URI, DB_FIELD_URI }, 
	            new int[] { android.R.id.text1, android.R.id.text2 });
        setListAdapter(mAdapter);

        // Defining custom titlebar
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.i_title);
        ((TextView)findViewById(R.id.title)).setText("TeamCity servers");
        ((Button)findViewById(R.id.title_right_btn)).setText("New");
        ((Button)findViewById(R.id.title_right_btn)).setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
                startActivityForResult(new Intent(ProjectWidgetConfigure.this, ServerPropertiesPage.class), NEW_SERVER_REQUEST);
			}
		});

        // Find the widget id from the intent. 
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
        }

        // If they gave us an intent without the widget id, just bail.
        if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
            finish();
        }

        mServersDB = openOrCreateDatabase(SERVERS_DATABASE_NAME, MODE_PRIVATE, null);
		mServersDB.execSQL("CREATE TABLE IF NOT EXISTS " + SERVERS_DATABASE_TABLE
				+ " ( _id INTEGER PRIMARY KEY autoincrement, " + DB_FIELD_URI + " VARCHAR, " + DB_FIELD_USERNAME + " VARCHAR, " + DB_FIELD_PASSWORD + " VARCHAR);");
		mC = mServersDB.query(SERVERS_DATABASE_TABLE, null, null, null, null, null, null);
		startManagingCursor(mC);
		mAdapter.changeCursor(mC);

        registerForContextMenu(getListView());
    }
    

	/* (non-Javadoc)
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		mServersDB.close();
		super.onDestroy();
	}

	/* (non-Javadoc)
	 * @see android.app.ListActivity#onListItemClick(android.widget.ListView, android.view.View, int, long)
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		
		Cursor c = mServersDB.query(SERVERS_DATABASE_TABLE, null, "_id = " + id, null, null, null, null);
		c.moveToFirst();

		Uri uri = Uri.parse(c.getString(c.getColumnIndex(DB_FIELD_URI)));
		//Re-create URI in order to make sure it's properly constructed
		String port = ":" + uri.getPort();
		if (uri.getPort() == -1)
			port = "";
		uri = Uri.parse
		(
			uri.getScheme()
				.concat("://")
				.concat(uri.getAuthority())
				.concat(port)
				.concat("/httpAuth/api/projects")
		);
				
		Intent intent = new Intent(ACTION_PICK_PROJECT,uri);
		intent.putExtra("username", c.getString(c.getColumnIndex(DB_FIELD_USERNAME)));
		intent.putExtra("password", c.getString(c.getColumnIndex(DB_FIELD_PASSWORD)));
		intent.setClassName("com.cdmdotnet.android.teamcity", "com.cdmdotnet.android.teamcity.ProjectListPage");
		
		c.close();
		
		startActivityForResult(intent, PICK_PROJECT_REQUEST);
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case PICK_PROJECT_REQUEST:
			if (resultCode == RESULT_OK) {
				data.putExtra("widget.id", mAppWidgetId);
				// Save data to preferences for future use by widget
				WidgetRegistry.getRegistry(this).saveWidgetPrefs(mAppWidgetId, data);

				//Wind up Alarm Service for widget updates
				//MonitorWidgetBroadcastReceiver.engageAlarmService(this);
				
				// Push widget to update surface with newly set BuildConfig URI
	        	data.setClass(this, ProjectWidgetUpdateService.class);
	            startService(data);

	            // Make sure we pass back the original appWidgetId
	            Intent resultValue = new Intent();
	            resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
	            setResult(RESULT_OK, resultValue);
	            finish();
			}
			break;
		case NEW_SERVER_REQUEST:
			if (resultCode == RESULT_OK) {
            	ContentValues cv = new ContentValues();
            	cv.put(DB_FIELD_URI, data.getData().toString());
            	cv.put(DB_FIELD_USERNAME, data.getStringExtra("username"));
            	cv.put(DB_FIELD_PASSWORD, data.getStringExtra("password"));
				mServersDB.insert(SERVERS_DATABASE_TABLE, "", cv);
				mC.requery();
				mAdapter.notifyDataSetChanged();
			}
			break;
		case EDIT_SERVER_REQUEST:
			if (resultCode == RESULT_OK) {
            	ContentValues cv = new ContentValues();
                cv.put(DB_FIELD_URI, data.getData().toString());
            	cv.put(DB_FIELD_USERNAME, data.getStringExtra("username"));
            	cv.put(DB_FIELD_PASSWORD, data.getStringExtra("password"));
				mServersDB.update(SERVERS_DATABASE_TABLE, cv, "_id = " + data.getLongExtra("id", -1), null);
				mC.requery();
				mAdapter.notifyDataSetChanged();
			}
			break;
		}
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.options_menu, menu);
	    return true;
	}
	
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo)
	 */
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.context_menu, menu);
	    menu.setHeaderTitle("Choose operation");
	}
	

	/* (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
		    case R.id.new_server:
				startActivityForResult(new Intent(this, ServerPropertiesPage.class), NEW_SERVER_REQUEST);
		        return true;
		    case R.id.quit:
		    	finish();
	    }
	    return false;
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onContextItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	    switch (item.getItemId()) {
		    case R.id.delete_server:
		    	deleteServer (info.id);
		        return true;
		    case R.id.edit_server:
		      	Intent sender = intentWithContext(new Intent (this, ServerPropertiesPage.class), info.id);
				startActivityForResult(sender, EDIT_SERVER_REQUEST);
		        return true;
			default:
		        return super.onContextItemSelected(item);
	    }
	}

	private void deleteServer(long id)
	{
		mServersDB.delete(SERVERS_DATABASE_TABLE, "_id = " + id, null);
		mC.requery();
		mAdapter.notifyDataSetChanged();
	}
	
	private Intent intentWithContext (Intent intent, long id) {
        Cursor c = mServersDB.query(SERVERS_DATABASE_TABLE, new String[] {DB_FIELD_URI, DB_FIELD_USERNAME, DB_FIELD_PASSWORD}, "_id = " + id, null, null, null, null); 
      	c.moveToFirst();
      	
      	intent.setData(Uri.parse(c.getString(c.getColumnIndex(DB_FIELD_URI))));
      	intent.putExtra("id", id);
      	intent.putExtra("username", c.getString(c.getColumnIndex(DB_FIELD_USERNAME)));
      	intent.putExtra("password", c.getString(c.getColumnIndex(DB_FIELD_PASSWORD)));
      	c.close();
		
		return intent;
	}
	
	
}

     
